import os

import cv2
import numpy as np

# ---------------------关于车牌的字典------------------------------
char2idx_dict = {"京": 0, "沪": 1, "津": 2, "渝": 3, "冀": 4, "晋": 5, "蒙": 6, "辽": 7, "吉": 8, "黑": 9, "苏": 10,
                 "浙": 11, "皖": 12, "闽": 13, "赣": 14, "鲁": 15, "豫": 16, "鄂": 17, "湘": 18, "粤": 19, "桂": 20,
                 "琼": 21, "川": 22, "贵": 23, "云": 24, "藏": 25, "陕": 26, "甘": 27, "青": 28, "宁": 29, "新": 30,
                 "0": 31, "1": 32, "2": 33, "3": 34, "4": 35, "5": 36, "6": 37, "7": 38, "8": 39, "9": 40,
                 "A": 41, "B": 42, "C": 43, "D": 44, "E": 45, "F": 46, "G": 47, "H": 48, "J": 49, "K": 50,
                 "L": 51, "M": 52, "N": 53, "P": 54, "Q": 55, "R": 56, "S": 57, "T": 58, "U": 59, "V": 60,
                 "W": 61, "X": 62, "Y": 63, "Z": 64}


# 生成一个数值与车牌字符的对应字典
def idx2char():
    return {f"{k}": v for k, v in enumerate(char2idx_dict.keys())}


idx2char_dict = idx2char()
# ----------------------------读取车牌并进行图像处理------------------------------
# 加载车牌信息(imread(图片路径,读取方式)  读取方式==0 灰度图)
img = cv2.imread("./img/panels/product/9ZSNJ.jpg")
# 原图的高宽：
img_h, img_w, _ = img.shape
# 灰度图
img_panel_gray = cv2.imread("./img/panels/product/9ZSNJ.jpg", 0)
# 取出黑白的二值化图
_, img_panel_binary = cv2.threshold(img_panel_gray, 127, 255, cv2.THRESH_BINARY)
# 针对二值化的图进行膨胀
kernel = np.ones((5, 5))
img_panel_binary = cv2.dilate(img_panel_binary, kernel)
# 寻找黑白图中的轮廓(外轮廓 RETR_EXTREL) --> (内轮廓 RETR_LIST)
contours, _ = cv2.findContours(img_panel_binary, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
# 定义一个存放坐标值的列表
num_list = []
# 循环所有的轮廓信息，并标注出来
for contour in contours:
    # 找出所有白色区域的最大外接矩形
    x, y, w, h = cv2.boundingRect(contour)
    if 20 // 14 <= w <= img_w // 7 and img_h // 2 <= h < img_h:
        # 针对字体较小的区域
        if w * h < 3000:
            x -= 15
            w += 30
        # 存放左上角坐标和右下角坐标
        num_list.append([x, y, x + w, y + h])

# ---------------------------------------用模板匹配进行预测------------------------
# 定义一个参数获取所有模板匹配后的值
tpl_result = []
# 切出所有的关于车牌信息的部分
for x1, y1, x2, y2 in num_list:
    chr_img = img_panel_gray[y1:y2, x1:x2]
    h, w = chr_img.shape
    # 反转颜色
    _, chr_img = cv2.threshold(chr_img, 127, 255, cv2.THRESH_BINARY_INV)
    # 获取目标图与所有的template的比较的值
    result = []
    for filename in range(0, 65):
        template = cv2.imread(f"./img/detect/{filename}.jpg", 0)
        template = cv2.resize(template, (w, h))
        result.append(cv2.matchTemplate(chr_img, template, cv2.TM_SQDIFF)[0, 0])
    tpl_result.append(result)

# --------------------------------获取结果并显示识别的车牌信息-----------------------
tpl_result = np.array(tpl_result)
# np.argmin以矩阵的水平方向取出该行的最小值对应的“下标（0-64）”
indices = np.argmin(tpl_result, axis=1)
s = ""
# indices[::-1] 输出该序列的逆反
for index in indices[::-1]:
    s += idx2char_dict[f"{index}"]
print(s)